package apigateway.controller;

import apigateway.requestAtomService.AtomServiceRunnable;
import apigateway.requestAtomService.ExcutePool;
import apigateway.serviceRegister.Anwser;
import apigateway.serviceRegister.CombinationServiceRegister;
import apigateway.serviceRegister.Dependecy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by 小泽玛丽罗 on 2017/3/5.
 */
@RestController
public class ServiceController {

    @Autowired
    private CombinationServiceRegister combinationServiceRegister;

    @Autowired
    private ExcutePool excutePool;
    @Value("${apigateway.ip}")
    private String apigatewayIp;

    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    private Anwser combination(@RequestParam(value = "uuid",required = false)String uuid){
        Anwser anwser=new Anwser();
        anwser.setType("combination");
        if(null!=combinationServiceRegister){
            List<Dependecy> dependecies=combinationServiceRegister
                    .getServiceNode().getDependencies();
            long start=System.currentTimeMillis();
            CountDownLatch countDownLatch=new CountDownLatch(dependecies.size());

            int index=0;
            for(Dependecy dependecy:dependecies){
                AtomServiceRunnable atomServiceRunnable=
                        new AtomServiceRunnable(anwser.getAnwsers(),index++,
                                apigatewayIp,dependecy,countDownLatch,uuid);
                excutePool.getAtomService(atomServiceRunnable);
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return anwser;
    }
}
